<?php

namespace Addons\Zmphoto\Controller;
use Addons\Zmphoto\Controller\BaseController;

class ZmphotoController extends BaseController{
	function _initialize() {
		parent::_initialize();
	}
    // 通用插件的列表模型
	public function lists() {
		$model_name = I("model",'photo_zm_activity');
		if(is_numeric($model_name)){
			$model_name = M('model')->where('id = '.$model_name)->getField('name');
		}
		$model = $this->getModel ($model_name);
		$model ||  $this->error ( '模型不存在' );
		// $map['uid']=$this->mid;
		// 
		// where  toekn 属于哪个公众号   aid  属于哪个活动   
		$map['aid']   = I('aid') ? I('aid') :null ;
		$map['token'] = get_token ();

		$imputbtn['url'] = U('impData',array('aid'=>I('aid')));
		$imputbtn['title'] = '导入用户数据';
		$morebtn[] = $imputbtn;
		$this->assign('top_more_button',$morebtn);

		// switch ($model_name){
		// 	case 'photo_data':
		// 	    //活动数据列表
		// 		$nav [0] ['title'] = "活动列表";
		// 		$nav [0] ['class'] = "";
		// 		$nav [0] ['url'] = U ( "lists" );
		// 		$nav [1] ['title'] = "活动数据";
		// 		$nav [1] ['class'] = "current";
		// 		$this->assign ( 'nav', $nav );
		// 		$outputbtn['url'] = U('expData');
		// 		$outputbtn['title'] = '导出用户数据';
		// 		$morebtn[] = $outputbtn;
		// 		$imputbtn['is_upload'] = true;
		// 		$imputbtn['url'] = U('impData',array('aid'=>I('aid')));
		// 		$imputbtn['title'] = '导入用户数据';
		// 		$morebtn[] = $imputbtn;
		// 		$this->assign('top_more_button',$morebtn);
		// 		$this->assign ( 'add_button', false );
		// 		$this->assign ( 'del_button', false );
		// 		$this->assign ( 'check_all', false );
		// 		break;
		//     case 'photo_gl':
		// 		 // 活动管理员列表
		// 		$nav [0] ['title'] = "活动列表";
		// 		$nav [0] ['class'] = "";
		// 		$nav [0] ['url'] = U ( "lists" );
		// 		$nav [1] ['title'] = "管理员列表";
		// 		$nav [1] ['class'] = "current";
		// 		$this->assign ( 'nav', $nav );
		// 		$btn['url']=U('lists',array('mdm'=>$_GET['mdm']));
		// 		$btn['title']='返回';
		// 		$morebtn[]=$btn;
		// 		$this->assign('top_more_button',$morebtn);
		// 		break;
		// }
		$this->assign('add_url',U('add',array('model'=>$model_name,'aid'=>I('aid'))));    //add-url
		$page = I('p',0,'intval');

		$list_data = $this->_get_model_list ( $model, $page, 'id desc',$map);
		$this->assign ( $list_data );
		$this->display ();
}

    /*添加*/
	public function add() {
	   $model_name = I("get.model",'photo_zm_activity');
		if(is_numeric($model_name)){
			$model_name = M('model')->where('id = '.$model_name)->getField('name');
		}
		$model = $this->getModel ($model_name);
		$model || $this->error ( '模型不存在！' );
		if (IS_POST) 
		{    
			//获取活动标识
			$aid = I('get.aid',0,'intval');
			if($aid){
				$aidArr = M('photo_zm_activity')->getField('id',true);
				if(!in_array($aid,$aidArr)){
					$this->error('当前活动标识不存在!');
				}else{
					$_POST['aid'] = $aid;
				}
			}
			//自动获取openid
			if($_POST['uid']){
				$_POST['openid'] = getOpenidByUid($_POST['uid']);
			}
			// 自动补充token
			$_POST ['token'] = get_token ();
			$_POST ['create_time'] = time();
			

			$Model = D ( parse_name ( get_table_name ( $model ['id'] ), 1 ) );
			// 获取模型的字段信息
			$Model = $this->checkAttr ( $Model, $model ['id'] );
            $Model->create ();
            if($_POST ['start']) $Model->start = strtotime($_POST ['start']);
            if($_POST ['over'])  $Model->over = strtotime($_POST ['over']);
			if ($id = $Model->add ()) {
				// 清空缓存
				method_exists ( $Model, 'clear' ) && $Model->clear ( $id, 'add' );
				$this->success ( '添加' . $model ['title'] . '成功！', U ( 'lists?model=' . $model ['name'], $this->get_param ) );
			} else {
				$this->error ( $Model->getError () );
			}
		} else {
			$nav [0] ['title'] = "活动列表";
			$nav [0] ['class'] = "";
			$nav [0] ['url'] = U ( "lists" );
			switch ($model_name) {
				case 'photo_zm_activity':
					$nav [1] ['title'] = "添加活动";
			        $nav [1] ['class'] = "current";
					break;
				case 'photo_zm_gl':
					$nav [1] ['title'] = "添加管理员";
					$nav [1] ['class'] = "current";
			}
			$this->assign ( 'nav', $nav );
			$fields = get_model_attribute ( $model ['id'] );

			$this->assign ( 'fields', $fields );
			$this->display ();
		}
}

    /*编辑*/
	public function edit() {
	    $model_name = I("model",'photo_zm_activity');
		if(is_numeric($model_name)){
			$model_name = M('model')->where('id = '.$model_name)->getField('name');
		}
		$model = $this->getModel ($model_name);
		$id = I ( 'id' );
		// 获取数据
		$data = M ( get_table_name ( $model ['id'] ) )->find ( $id );
		$data || $this->error ( '数据不存在！' );
		if (IS_POST) {
			$_POST ['update_time'] = time();
			$Model = D ( parse_name ( get_table_name ( $model ['id'] ), 1 ) );
			// 获取模型的字段信息
			$Model = $this->checkAttr ( $Model, $model ['id'] );
			if ($Model->create () && $Model->save ()) {
				// 清空缓存
				method_exists ( $Model, 'clear' ) && $Model->clear ( $id, 'edit' );
				$this->success ( '保存' . $model ['title'] . '成功！', U ( 'lists?model=' . $model ['name'], $this->get_param ) );
			} else {
				$this->error ( $Model->getError () );
			}
		} else {
            switch ($model_name){
			case 'photo_zm_data':
			    //活动数据列表
				$nav [0] ['title'] = "活动数据列表";
				$nav [0] ['class'] = "";
				$nav [0] ['url'] = U ( "lists",array('model'=>$model_name));
				$this->assign ( 'nav', $nav );
				break;
		    case 'photo_gl':
				 // 活动管理员列表
				$nav [0] ['title'] = "管理员列表";
				$nav [0] ['class'] = "";
				$nav [0] ['url'] = U ( "lists",array('model'=>$model_name));
				$this->assign ( 'nav', $nav );
				break;
		}
			$fields = get_model_attribute ( $model ['id'] );
			$this->assign ( 'fields', $fields );
			$this->assign ( 'data', $data );
			$this->display ();
		}
}

    /*查看用户详细数据*/
    public function userInfo(){
    	$model_name = I("model",'photo_zm_activity');
		if(is_numeric($model_name)){
			$model_name = M('model')->where('id = '.$model_name)->getField('name');
		}
    	$nav [0] ['title'] = "活动数据";
		$nav [0] ['class'] = "";
		$nav [0] ['url'] = 'javascript:window.history.back()';
		$nav [1] ['title'] = "活动数据";
		$nav [1] ['class'] = "current";
		$this->assign ( 'nav', $nav );
       $info = M('PhotoZmData')->where('id = '.I('aid'))->find();
       $this->assign('info',$info);
       $this->display();
}
    
    public function exportExcel($expTitle,$expCellName,$expTableData){
        $xlsTitle = iconv('utf-8', 'gb2312', $expTitle);//文件名称
        $fileName = $_SESSION['account'].date('_YmdHis');//or $xlsTitle 文件名称可根据自己情况设定
        $cellNum = count($expCellName);
        $dataNum = count($expTableData);
        
        vendor ( "PHPExcel" );
          
        $objPHPExcel = new \PHPExcel();
        $cellName = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ');
        
        $objPHPExcel->getActiveSheet(0)->mergeCells('A1:'.$cellName[$cellNum-1].'1');//合并单元格
       // $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $expTitle.'  Export time:'.date('Y-m-d H:i:s'));  
        for($i=0;$i<$cellNum;$i++){
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i].'2', $expCellName[$i][1]); 
        } 
          // Miscellaneous glyphs, UTF-8   
        for($i=0;$i<$dataNum;$i++){
          for($j=0;$j<$cellNum;$j++){
            $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j].($i+3), $expTableData[$i][$expCellName[$j][0]]);
          }             
        }  
        
        header('pragma:public');
        header('Content-type:application/vnd.ms-excel;charset=utf-8;name="'.$xlsTitle.'.xls"');
        header("Content-Disposition:attachment;filename=$fileName.xls");//attachment新窗口打印inline本窗口打印
		$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');  
        $objWriter->save('php://output'); 
        exit;   
 }
/**
     *
     * 导出Excel
     */
    public function expData(){//导出Excel
    	$id = I('get.id');
        $xlsName  = "UserData";
        $xlsCell  = array(
        array('id','序列'),
        array('no','学号'),
        array('department','学院'),
        array('major','专业'),
        array('class','班级'),
        array('username','姓名'),   
        array('photo_url','图片地址'),        
        );
        $xlsModel = M('PhotoZmData');
        $map['id'] = $id;
        $map['status'] = 1;
        $map['confirm'] = 1;
        $xlsData  = $xlsModel->field('id,no,department,major,class,username,photo_url')->where($map)->order('department DESC')->select();
        foreach ($xlsData as $k => $v)
        {
            $xlsData[$k]['photo_url']= get_file_url($xlsData[$k]['photo_url']);
        }
        $this->exportExcel($xlsName,$xlsCell,$xlsData);
         
    }
    
    /*导入用户数据*/
    function impData(){
    	if(IS_POST){
    		$aid = I('post.aid',0,'intval');
    		$map['id'] = $aid;
    		$map['status'] = 1;
    		$map['token'] = get_token();
    		if(!$aid || ! M('photo_zm_activity')->field('id,actname')->where($map)->find())   $this->error('请选择活动');

    		if (!empty($_FILES)) {
            $upload = new \Think\Upload();// 实例化上传类
			$upload->maxSize = 3145728 ;// 设置附件上传大小
			$upload->exts = array('xlsx', 'xls');// 设置附件上传类型
			$upload->savePath = ''; // 设置附件上传目录
			$upload->replace = true; // 覆盖文件
			// 单文件上传
			$info = $upload->uploadOne($_FILES['field']);
			if(!$info) {
			// 上传错误提示错误信息
			$this->show($upload->getError());
			}
                vendor("PHPExcel");
                $file_name='./Uploads/'.$info['savepath'].$info['savename'];
                $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
                $objPHPExcel = $objReader->load($file_name,$encode='utf-8');
                $sheet = $objPHPExcel->getSheet(0);
                $highestRow = $sheet->getHighestRow(); // 取得总行数
                $highestColumn = $sheet->getHighestColumn(); // 取得总列数
                $arr = array();
                $token = get_token();
                $time = time();
                for($i=2;$i<=$highestRow;$i++)
                {   
                   $data['aid'] = $aid;
                   $data['token'] = $token;
                   $data['no'] = $objPHPExcel->getActiveSheet()->getCell("A".$i)->getValue();  
                   $data['card_id'] = $objPHPExcel->getActiveSheet()->getCell("B".$i)->getValue();  
                   $data['department'] = $objPHPExcel->getActiveSheet()->getCell("C".$i)->getValue();
                   $data['major'] = $objPHPExcel->getActiveSheet()->getCell("D".$i)->getValue();
                   $data['grade'] = $objPHPExcel->getActiveSheet()->getCell("E".$i)->getValue();
                   $data['class'] = $objPHPExcel->getActiveSheet()->getCell("F".$i)->getValue();
                   $data['password'] = $objPHPExcel->getActiveSheet()->getCell("G".$i)->getValue();
                   $data['username'] = $objPHPExcel->getActiveSheet()->getCell("H".$i)->getValue();
                   $data['mobile'] = $objPHPExcel->getActiveSheet()->getCell("I".$i)->getValue();
                   $arr[] = $data;
                } 
                 M('PhotoZmData')->addAll($arr);
                 $this->success('导入成功!',U('lists'));
        }else
            {
                $this->error("请选择上传的文件");
            } 
    	}else{
    		$this->assign('actData',M('photo_zm_activity')->field('id,actname')->where(array('status'=>1,'token'=>get_token()))->select());
    		$this->display();
    	}   
}

    // 获取模型列表数据
	public function _get_model_list($model = null, $page = 0, $order = 'id desc',$where=null) {
		if (empty ( $model ))
			return false;
		$page || $page = I ( 'p', 1, 'intval' ); // 默认显示第一页数据
		                                         
		// 解析列表规则
		$list_data = $this->_list_grid ( $model );
		$fields = $list_data ['fields'];
		
		// 搜索条件
		$map = $this->_search_map ( $model, $fields );
		$row = empty ( $model ['list_row'] ) ? 20 : $model ['list_row'];
		
		// 读取模型数据列表
		
		if ($model['name'] != 'user'){
		    empty ( $fields ) || in_array ( 'id', $fields ) || array_push ( $fields, 'id' );
		   
		}else{
		    empty ( $fields ) || in_array ( 'uid', $fields ) || array_push ( $fields, 'uid' );
		    $order='uid desc';
		}
		
		$name = parse_name ( get_table_name ( $model ['id'] ), true );
		$data = M ( $name )->field ( empty ( $fields ) ? true : $fields )->where ( $where )->order ( $order )->page ( $page, $row )->select ();
		/* 查询记录总数 */
		$count = M ( $name )->where ( $where )->count ();
		
		$list_data ['list_data'] = $data;
		
		// 分页
		if ($count > $row) {
			$page = new \Think\Page ( $count, $row );
			$page->setConfig ( 'theme', '%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%' );
			$list_data ['_page'] = $page->show ();
		}
		
		return $list_data;
}

	function preview(){
		$id = I ( 'id', 0, 'intval' );
		$url = addons_url( 'Zmphoto://Wap/index/id/'.$id);
		$this -> assign('url',$url);
		$this->display ( SITE_PATH . '/Application/Home/View/default/Addons/preview.html' );
	}

}


